package com.kingcore.director.reminder.ui;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.util.Date;

import javax.swing.ButtonGroup;
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.undo.UndoManager;

import org.apache.log4j.Logger;

import wzw.beans.CodeNameBean;
import wzw.beans.DbBean;
import wzw.swing.calendar.DatePicker;
import wzw.util.ComponentUtil;

import com.kingcore.director.DirectorConstants;
import com.kingcore.director.base.ui.DirectorDialog;
import com.kingcore.director.core.util.DirectorComponentUtils;
import com.kingcore.director.core.util.DirectorStringUtils;
import com.kingcore.director.core.util.Formatter;
import com.kingcore.director.main.MainFrame;
import com.kingcore.framework.context.ApplicationContext;
import com.kingcore.framework.context.DatabaseManager;
import com.sunking.swing.JNumberField;

public class AwokeEditDialog extends DirectorDialog 
		implements ActionListener,ChangeListener, ItemListener, KeyListener{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel mainPanel = null;
	private JTabbedPane mainTabPane = null;
	private JPanel general = null;
	private JPanel loop = null;
	private JPanel advanced = null;
	private JLabel jLabel = null;
	private JTextField awokeTitle = null;
	private JLabel jLabel1 = null;
	private JComboBox type = null;
	private JComboBox awokeStyle = null;
	private JScrollPane sp_content = null;
	private JTextArea content = null;
	private JLabel jLabel2 = null;
	private JLabel jLabel_AwokeStyle = null;
	private JComboBox beginTime = null;
	private JCheckBox isLoop = null;
	private JPanel loop_p1 = null;
	private JRadioButton minute = null;
	private JRadioButton hour = null;
	private JRadioButton day = null;
	private JRadioButton week = null;
	private JRadioButton month = null;
	private JRadioButton year = null;
	private JLabel jLabel3 = null;
	private JButton btn_enter = null;
	private JButton btn_cancel = null;
	private JCheckBox useful = null;
	private JCheckBox needAffirm = null;
	private String id = null;
	private JLabel jLabel4 = null;
	private JTextField intervalNum = null;
	private JLabel lblTx = null;
	private MainFrame mainFrame=null;
	private Logger log = Logger.getLogger( AwokeEditDialog.class );
	/**
	 * @return Returns the id.
	 */
	public String getId() {
		return id;
	}

	/**
	 * @param id The id to set.
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * This method initializes jTabbedPane	
	 * 	
	 * @return javax.swing.JTabbedPane	
	 */
	private JTabbedPane getMainTabPane() {
		if (mainTabPane == null) {
			mainTabPane = new JTabbedPane();
			mainTabPane.setBounds(new java.awt.Rectangle(13,7,461,298));
			mainTabPane.addTab("提醒", null, getGeneral(), null);
			mainTabPane.addTab("循环设置", null, getLoop(), null);
			mainTabPane.addTab("高级动作设置", null, getAdvanced(), null);
			mainTabPane.addChangeListener(this);
		}
		return mainTabPane;
	}

	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getGeneral() {
		if (general == null) {
			jLabel = new JLabel();
			jLabel.setBounds(new java.awt.Rectangle(11,15,59,23));
			jLabel.setText("标题：");
			general = new JPanel();
			general.setLayout(null);
			general.add(jLabel, null);
			general.add(getAwokeTitle(), null);
			jLabel1 = new JLabel();
			jLabel1.setBounds(new java.awt.Rectangle(251,15,73,23));
			jLabel1.setText("所属群组：");
			general.add(jLabel1, null);
			general.add(getType(), null);
			general.add(getSp_content(), null);
			jLabel2 = new JLabel();
			jLabel2.setBounds(new java.awt.Rectangle(12,195,122,23));
			jLabel2.setText("提醒开始时间：");
			general.add(jLabel2, null);
			general.add(getBeginTime(), null);
			jLabel_AwokeStyle = new JLabel();
			jLabel_AwokeStyle.setBounds(new java.awt.Rectangle(12,226,122,23));
			jLabel_AwokeStyle.setText("提醒风格：");
			general.add(jLabel_AwokeStyle, null);
			general.add(getAwokeStyle(), null);
		}
		return general;
	}

	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getLoop() {
		if (loop == null) {
			loop = new JPanel();
			loop.setLayout(null);
			loop.add(getIsLoop(), null);
			loop.add(getLoop_p1(), null);
		}
		return loop;
	}

	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getAdvanced() {
		if (advanced == null) {
			advanced = new JPanel();
			advanced.setLayout(null);
			advanced.add(getIsOpenFile(), null);
			JLabel lbl_location = new JLabel("程序：");
			lbl_location.setBounds(new java.awt.Rectangle(35,38,38,25));
			advanced.add(lbl_location, null);
			advanced.add(getOpenFileLocation(), null);
			advanced.add(getFileSelectButton(), null);

			JLabel lbl_params = new JLabel("参数：");
			lbl_params.setBounds(new java.awt.Rectangle(35,68,38,25));
			advanced.add(lbl_params, null);
			advanced.add(getOpenParams(), null);
		}
		return advanced;
	}

	private JButton fileSelectButton = null;
	private JButton getFileSelectButton() {
		if(fileSelectButton==null){
			fileSelectButton = new JButton();
			fileSelectButton.addActionListener(this);
			fileSelectButton.setText("...");
			fileSelectButton.setBounds(new java.awt.Rectangle(400,36,28,28));
			fileSelectButton.setEnabled(false);
		}
		return fileSelectButton;
	}

	/**
	 * This method initializes jCheckBox	
	 * 	
	 * @return javax.swing.JCheckBox	
	 */
	public JTextField openFileLocation = null;
	public JTextField getOpenFileLocation() {
		if (openFileLocation == null) {
			openFileLocation = new JTextField();
			openFileLocation.setBounds(new java.awt.Rectangle(75,38,325,25));
			openFileLocation.setEnabled(false);  //默认不可用
//			isLoop.addChangeListener(this);
//			openFileLocation.addItemListener(this);
		}
		return openFileLocation;
	}
	
	public JTextField openParams = null;
	public JTextField getOpenParams() {
		if (openParams == null) {
			openParams = new JTextField();
			openParams.setBounds(new java.awt.Rectangle(75,68,325,25));
			openParams.setEnabled(false);
		}
		return openParams;
	}

	public JCheckBox isOpenFile = null;
	/**
	 * This method initializes jCheckBox	
	 * 	
	 * @return javax.swing.JCheckBox	
	 */
	public JCheckBox getIsOpenFile() {
		if (isOpenFile == null) {
			isOpenFile = new JCheckBox();    //默认未选中
			isOpenFile.setBounds(new java.awt.Rectangle(15,8,185,25));
			isOpenFile.setText("提醒时直接运行程序");
//			isLoop.addChangeListener(this);
			isOpenFile.addItemListener(this);
		}
		return isOpenFile;
	}

	/**
	 * This method initializes jTextField	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	public JTextField getAwokeTitle() {
		if (awokeTitle == null) {
			awokeTitle = new JTextField();
			awokeTitle.setBounds(new java.awt.Rectangle(50,14,190,25));
			awokeTitle.requestFocus();
			awokeTitle.requestFocusInWindow();
		}
		return awokeTitle;
	}

	/**
	 * This method initializes jComboBox	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getType() {
		if (type == null) {
			type = new JComboBox();
			type.setRenderer( new AwokeTypeRenderer() );
			type.setBounds(new java.awt.Rectangle(320,14,124,25));
			ComponentUtil.initComboBox(type, DirectorConstants.Data_AwokeTypes );
			
			//type.setRenderer( null );
		}
		return type;
	}

	/**
	 * This method initializes jComboBox	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getAwokeStyle() {
		if (awokeStyle == null) {
			awokeStyle = new JComboBox();
			//awokeStyle.setRenderer( new AwokeTypeRenderer() );
			awokeStyle.setBounds(new java.awt.Rectangle(105,226,160,23));

			ComponentUtil.initComboBox(awokeStyle,new String[][]{
								{DirectorConstants.AwokeStyle_Normal,"普通提醒风格"},
								{DirectorConstants.AwokeStyle_MsnTips,"MSN提醒风格"} }
			);
			awokeStyle.setSelectedIndex(1) ;
			//type.setRenderer( null );			
		}
		return awokeStyle;
	}
	
	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getSp_content() {
		if (sp_content == null) {
			sp_content = new JScrollPane();
			sp_content.setBounds(new java.awt.Rectangle(14,47,430,141));
			sp_content.setViewportView(getContent());
		}
		return sp_content;
	}

	/**
	 * This method initializes jTextArea	
	 * 	
	 * @return javax.swing.JTextArea	
	 */
	public JTextArea getContent() {
		if (content == null) {
			content = new JTextArea();
			
			content.addKeyListener(this);
		}
		return content;
	}


	// ------------------- implement for redo and undo begin
	protected void editUndo(){
	   if (undoManager.canUndo()){
		   undoManager.undo();
		}
	}
	
	protected void editRedo(){
	   if (undoManager.canRedo()){
		   undoManager.redo();
		}
	}
	private UndoManager undoManager = null; 
	private UndoManager getUndoManager(){
		if (undoManager==null) {
			undoManager = new UndoManager(); // {
		}
		return undoManager;
	}
	// ------------------- implement for redo and undo end
	

	/**
	 * This method initializes jComboBox	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getBeginTime() {
		if (beginTime == null) {
			beginTime = new DatePicker(DatePicker.STYLE_CN_DATETIME1);	//JComboBox
			beginTime.setBounds(new java.awt.Rectangle(105,195,160,23));
		}
		return beginTime;
	}

	/**
	 * This method initializes jComboBox	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	public void initBeginTime(String str) {
		if (str != null) {
			try {
				DateFormat df =  new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = df.parse(str);
				((DatePicker)getBeginTime()).setSelectedDate(date);
			
			} catch (Exception e) {
				e.printStackTrace();
			}
		} 
	}
	
	/**
	 * This method initializes jCheckBox	
	 * 	
	 * @return javax.swing.JCheckBox	
	 */
	public JCheckBox getIsLoop() {
		if (isLoop == null) {
			isLoop = new JCheckBox();
			isLoop.setBounds(new java.awt.Rectangle(15,8,185,25));
			isLoop.setText("循环会按规律重复发生");
//			isLoop.addChangeListener(this);
			isLoop.addItemListener(this);
		}
		return isLoop;
	}

	ButtonGroup bg_type=null;
	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getLoop_p1() {
		if (loop_p1 == null) {
			loop_p1 = new JPanel();
			lblTx = new JLabel();
			lblTx.setBounds(new java.awt.Rectangle(187,12,65,26));
			lblTx.setText("提醒");
			jLabel4 = new JLabel();
			jLabel4.setBounds(new java.awt.Rectangle(111,13,26,21));
			jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
			jLabel4.setText("每");
			jLabel3 = new JLabel();
			jLabel3.setBounds(new java.awt.Rectangle(77,8,1,110));
			jLabel3.setText("JLabel");
			loop_p1.setLayout(null);
			loop_p1.setBounds(new java.awt.Rectangle(14,36,452,239));
			loop_p1.add(getMinuteRadio(), null);
			loop_p1.add(getHourRadio(), null);
			loop_p1.add(getDayRadio(), null);
			loop_p1.add(getWeekRadio(), null);
			loop_p1.add(getMonthRadio(), null);
			loop_p1.add(getYearRadio(), null);
			loop_p1.add(jLabel3, null);
			loop_p1.add(jLabel4, null);
			loop_p1.add(getIntervalNum(), null);
			loop_p1.add(lblTx, null);
//			loop_p1.add(getWeekSelector(), null);

			bg_type=new ButtonGroup();
			bg_type.add(getMinuteRadio() );
			bg_type.add(getHourRadio() );
			bg_type.add(getDayRadio() );
			bg_type.add(getWeekRadio() );
			bg_type.add(getMonthRadio() );
			bg_type.add(getYearRadio() );

		}
		return loop_p1;
	}


	private void setLoopEnabled(boolean selected) {
		lblTx.setEnabled(selected);
		jLabel3.setEnabled(selected);
		jLabel4.setEnabled(selected); 
		
		getMinuteRadio().setEnabled(selected); 
		getHourRadio().setEnabled(selected); 
		getDayRadio().setEnabled(selected); 
		getWeekRadio().setEnabled(selected); 
		getMonthRadio().setEnabled(selected); 
		getYearRadio().setEnabled(selected);
		getIntervalNum().setEnabled(selected); 
	}

//	private JCheckBox ckb_1 = null;
//	private JCheckBox ckb_2 = null;
//	private JCheckBox ckb_3 = null;
//	private JCheckBox ckb_4 = null;
//	private JCheckBox ckb_5 = null;
//	private JCheckBox ckb_6 = null;
//	private JCheckBox ckb_7 = null;
	private JPanel weekSelector = null;
	
	/**
	 * 提醒时间复选：周一、周二、、、周日
	 * 
	 * @return
	 */
	private JPanel getWeekSelector() {
		if(weekSelector==null){
			weekSelector = new JPanel();
//			weekSelector.setBounds(new java.awt.Rectangle(100,32,300,26));
//			ckb_1 = new JCheckBox("1");
//			ckb_2 = new JCheckBox("2");
//			ckb_3 = new JCheckBox("3");
//			ckb_4 = new JCheckBox("4");
//			ckb_5 = new JCheckBox("5");
//			ckb_6 = new JCheckBox("6");
//			ckb_7 = new JCheckBox("7");
//			weekSelector.add(ckb_1);
//			weekSelector.add(ckb_2);
//			weekSelector.add(ckb_3);
//			weekSelector.add(ckb_4);
//			weekSelector.add(ckb_5);
//			weekSelector.add(ckb_6);
//			weekSelector.add(ckb_7);
		}
		return weekSelector;
	}

	/**
	 * This method initializes jRadioButton	
	 * 	
	 * @return javax.swing.JRadioButton	
	 */
	public JRadioButton getMinuteRadio() {
		if (minute == null) {
			minute = new JRadioButton();
			minute.setBounds(new java.awt.Rectangle(14,7,73,19));
			minute.setText("分");
			minute.addActionListener(this);
			// 鼠标在上面经过、移动，都为触发 stateChanged 事件，故在此不采用。
			//minute.addChangeListener(this);
		}
		return minute;
	}

	/**
	 * This method initializes jRadioButton1	
	 * 	
	 * @return javax.swing.JRadioButton	
	 */
	public JRadioButton getHourRadio() {
		if (hour == null) {
			hour = new JRadioButton();
			hour.setBounds(new java.awt.Rectangle(14,26,73,19));
			hour.setText("时");
			hour.addActionListener(this);
			//hour.addChangeListener(this);
		}
		return hour;
	}

	/**
	 * This method initializes jRadioButton2	
	 * 	
	 * @return javax.swing.JRadioButton	
	 */
	public JRadioButton getDayRadio() {
		if (day == null) {
			day = new JRadioButton();
			day.setBounds(new java.awt.Rectangle(14,45,73,19));
			day.setText("天");
			day.setSelected(true);
			day.addActionListener(this);
			//day.addChangeListener(this);
		}
		return day;
	}

	/**
	 * This method initializes jRadioButton3	
	 * 	
	 * @return javax.swing.JRadioButton	
	 */
	public JRadioButton getWeekRadio() {
		if (week == null) {
			week = new JRadioButton();
			week.setBounds(new java.awt.Rectangle(14,64,73,19));
			week.setText("周");
			week.addActionListener(this);
			//week.addChangeListener(this);
		}
		return week;
	}

	/**
	 * This method initializes jRadioButton4	
	 * 	
	 * @return javax.swing.JRadioButton	
	 */
	public JRadioButton getMonthRadio() {
		if (month == null) {
			month = new JRadioButton();
			month.setBounds(new java.awt.Rectangle(14,83,73,19));
			month.setText("月");
			month.addActionListener(this);
			//month.addChangeListener(this);
		}
		return month;
	}

	/**
	 * This method initializes jRadioButton5	
	 * 	
	 * @return javax.swing.JRadioButton	
	 */
	public JRadioButton getYearRadio() {
		if (year == null) {
			year = new JRadioButton();
			year.setBounds(new java.awt.Rectangle(14,102,73,19));
			year.setText("年");
			year.addActionListener(this);
			//year.addChangeListener(this);
		}
		return year;
	}

	/**
	 * This method initializes jButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtn_enter() {
		if (btn_enter == null) {
			btn_enter = new JButton();
			btn_enter.setBounds(new java.awt.Rectangle(271,309,80,28));
			btn_enter.setText("确认(O)");
			btn_enter.setMnemonic('O');
			btn_enter.addActionListener(this);
		}
		return btn_enter;
	}

	/**
	 * This method initializes jButton1	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtn_cancel() {
		if (btn_cancel == null) {
			btn_cancel = new JButton();
			btn_cancel.setBounds(new java.awt.Rectangle(357,309,85,28));
			btn_cancel.setText("关闭(C)");
			btn_cancel.setMnemonic('C');
			btn_cancel.addActionListener(this);
		}
		return btn_cancel;
	}

	/**
	 * This method initializes jCheckBox	
	 * 	
	 * @return javax.swing.JCheckBox	
	 */
	private JCheckBox getUseful() {
		if (useful == null) {
			useful = new JCheckBox();
			useful.setBounds(new java.awt.Rectangle(14,310,89,26));
			useful.setText("提醒有效");
			useful.setSelected(true);
		}
		return useful;
	}

	/**
	 * This method initializes jCheckBox1	
	 * 	
	 * @return javax.swing.JCheckBox	
	 */
	private JCheckBox getNeedAffirm() {
		if (needAffirm == null) {
			needAffirm = new JCheckBox();
			needAffirm.setBounds(new java.awt.Rectangle(106,310,140,26));
			needAffirm.setText("提醒需要确认");
			needAffirm.setSelected(true);
		}
		return needAffirm;
	}
	
	/**
	 * This method initializes jTextField	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	public JTextField getIntervalNum() {
		if (intervalNum == null) {
			intervalNum = new JNumberField(5);  //new JTextField();
			intervalNum.setText("1");
			intervalNum.setBounds(new java.awt.Rectangle(144,13,37,23));
		}
		return intervalNum;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		AwokeEditDialog ap = new AwokeEditDialog();
		ap.show();

	}

	/**
	 * This is the default constructor
	 */
	public AwokeEditDialog() {
		this(null);
	}

	public AwokeEditDialog(MainFrame frame) {
		this(frame, null);
	}
	
	private String awokeId = null;
	public AwokeEditDialog(MainFrame frame, String id) {
		//***传入frame,表示模态窗口的父对象；使用模态窗口会导致提示窗口的alwaysOnTop属性暂时失效
		super(frame, false); 
		this.mainFrame = frame;
		this.awokeId = id;
		initialize();
		fetchData(this.awokeId);
		getContent().getDocument().addUndoableEditListener( getUndoManager() );//取数后增加redo and undo
		//this.setModal(true);
		this.getAwokeTitle().requestFocus();
		this.getAwokeTitle().requestFocus(true);
		this.getAwokeTitle().requestFocusInWindow();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		// System.out.println("initialize");
		this.setSize(490, 372);
		this.setTitle("新增提醒窗口");
		this.setResizable(false);
		this.setContentPane(getJContentPane());
		
		//set init value
		JTree tree = this.mainFrame.getReminderMainPanel().getTree();
		Object obj =  ((DefaultMutableTreeNode) tree
				.getLastSelectedPathComponent()).getUserObject() ;
		if (obj!=null) {
			String code = ((CodeNameBean)obj).getCode();
			ComponentUtil.setSelectedItemByCode( getType(),code );
		}
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (mainPanel == null) {
			mainPanel = new JPanel();
			mainPanel.setLayout(null);
			mainPanel.add(getMainTabPane(), null);
			mainPanel.add(getBtn_enter(), null);
			mainPanel.add(getBtn_cancel(), null);
			mainPanel.add(getUseful(), null);
			mainPanel.add(getNeedAffirm(), null);
		}
		return mainPanel;
	}


    private class AwokeTypeRenderer extends DefaultListCellRenderer {
        Icon tutorialIcon;

        public AwokeTypeRenderer() {
            this(null) ;
        }
        
        public AwokeTypeRenderer(Icon icon) {
            tutorialIcon = icon;
        }


		public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {

            super.getListCellRendererComponent(
            		list, value, index,isSelected, cellHasFocus );
            
            //System.out.println("index="+index);
            String code = ((CodeNameBean)value).getCode();
            if(code!=null){
            	if(code.equals("00")){
            		setIcon( DirectorComponentUtils.createImageIcon("./resource/tree_00.gif") );
            	} else if(code.equals("0000")){
            		setIcon( DirectorComponentUtils.createImageIcon("./resource/tree_0000.gif") );
            	} else if(code.equals("0001")){
            		setIcon( DirectorComponentUtils.createImageIcon("./resource/tree_0001.gif") );
            	} else if(code.equals("0002")){
            		setIcon( DirectorComponentUtils.createImageIcon("./resource/tree_0002.gif") );
            	} else if(code.equals("0003")){
            		setIcon( DirectorComponentUtils.createImageIcon("./resource/tree_0003.gif") );
            	} else if(code.equals("0004")){
            		setIcon( DirectorComponentUtils.createImageIcon("./resource/tree_0004.gif") );
            	} else if(code.equals("0005")){
            		setIcon( DirectorComponentUtils.createImageIcon("./resource/tree_0005.gif") );
            	} else if(code.equals("99")){
            		setIcon( DirectorComponentUtils.createImageIcon("./resource/tree_99.gif") );
            	} else {
            		setIcon( DirectorComponentUtils.createImageIcon("./resource/tree_00.gif") );
            	}
            }
            
            return this;
		}
    }

    /**
     * 实现 ActioinListener 监听器的方法
     */
	public void actionPerformed(ActionEvent event) {
		Object obj=event.getSource();
		// toolBar
		if( obj == btn_enter ){	
			int int_id=0;
			String str_title= getAwokeTitle().getText();
			String str_type= ComponentUtil.getSelectedItemCode( getType() );
			String str_awokeStyle= ComponentUtil.getSelectedItemCode( getAwokeStyle() );
			String str_beginTime= getBeginTime().getSelectedItem().toString();
			String str_content= getContent().getText();
			String str_useful= getUseful().isSelected()?"Y":"N";
			String str_needAffirm= getNeedAffirm().isSelected()?"Y":"N";
			String str_timeType="Y";	// 阳历
			String str_interval="0";	// 不循环
			String str_intervalNum="0";
			String str_isOpenFile="0";
			if( getIsOpenFile().isSelected() ){
				str_isOpenFile="1";
			}
			String str_fileUrl = toStringValue(getOpenFileLocation().getText());
			String str_openParams = toStringValue(getOpenParams().getText());
			if( getIsLoop().isSelected() ){
				str_intervalNum = getIntervalNum().getText();
				if(str_intervalNum==null || str_intervalNum.trim().equals("")){
					JOptionPane.showMessageDialog(this,"请输入循环数！");
					getIntervalNum().requestFocus();
					return;
				}
				str_intervalNum = str_intervalNum.trim();
				if( this.getMinuteRadio().isSelected() ){
					str_interval="minute";
				} else if( this.getHourRadio().isSelected() ){
					str_interval="hour";
				} else if( this.getDayRadio().isSelected() ){
					str_interval="day";
				} else if( this.getWeekRadio().isSelected() ){
					str_interval="week";
				} else if( this.getMonthRadio().isSelected() ){
					str_interval="month";
				} else if( this.getYearRadio().isSelected() ){
					str_interval="year";
				} else {
					JOptionPane.showMessageDialog(this,"请输入循环类型！");
					return;
				}
			} else {
				str_interval="0";
			}
			if ( str_title==null || str_title.trim().equals("")) {
				JOptionPane.showMessageDialog(this,"请输入提醒的标题！");
				getAwokeTitle().requestFocus();
				return;
			}
			if ( str_content==null || str_content.trim().equals("")) {
				JOptionPane.showMessageDialog(this,"请输入提醒的内容！");
				getContent().requestFocus();
				return;
			}
			
			// checked end, begin database operation...
			String sql="";
			try {
				//建议保留.getDatabaseManager()方法，作为一种简单的方式
				DatabaseManager dbManager = ApplicationContext.getInstance().getDatabaseManager();
				Date dt_nextTime = DirectorStringUtils.getNextBeginTime(str_beginTime
							,str_interval,str_intervalNum);
				if( getId()==null ){   // add a new awoke
	
					// 取id
					Connection conn = null;
					Statement stmt=null;
					ResultSet rs=null;
					try { 
						conn= ApplicationContext.getInstance().getDataSourceManager().getConnection();
						sql="SELECT max(ID) AS MAXID FROM "+DirectorConstants.RMD_Awoke;
						stmt=conn.createStatement();
						rs=stmt.executeQuery(sql);
						if(rs.next()){
							int_id = rs.getInt("MAXID") + 1;
						}else{
							int_id = 0;
						}
	
					} catch (SQLException e1) {
						JOptionPane.showMessageDialog(this,e1.getMessage(),"查询失败",JOptionPane.ERROR_MESSAGE);
						e1.printStackTrace();						
					} finally{
						//释放资源
						wzw.util.DbUtils.closeQuietly(conn, stmt, rs);
					}
					
					// 2006-9-20 set NEXTTIME equal BEGINTIME
					sql="Insert Into "+DirectorConstants.RMD_Awoke+"( ID,TYPE, TITLE, BEGINTIME, NEXTTIME, TIMETYPE, INTERVAL,INTERVALNUM, USEFUL" +
							", NEEDAFFIRM, CONTENT,Is_Open_File,File_Url,Open_Params,awokeStyle) " +
							"VALUES('"+int_id+"','"
								      +str_type+"','"
								      +dbManager.escape2Sql(str_title)+"','"
								      +str_beginTime+"','"
								      +Formatter.format(dt_nextTime,"yyyy-MM-dd HH:mm:ss")+"','"
								      +str_timeType+"','"
								      +str_interval+"',"
								      +str_intervalNum+",'"
								      +str_useful+"','"
								      +str_needAffirm+"','"
								      +dbManager.escape2Sql(str_content)+"','"
								      +str_isOpenFile+"','"
								      +str_fileUrl+"','"
								      +str_openParams+"','"
								      +str_awokeStyle+"')";
				} else {   // update a awoke
					sql="Update "+DirectorConstants.RMD_Awoke+" " +
							"Set TYPE='"+str_type+"', " +
								"TITLE='"+dbManager.escape2Sql(str_title)+"', " +
								"BEGINTIME='"+str_beginTime+"'," +
								"NEXTTIME='"+ Formatter.format(dt_nextTime,"yyyy-MM-dd HH:mm:ss")+"'," +
								"TIMETYPE='"+str_timeType+"'," +
								"INTERVAL='"+str_interval+"'," +
								"INTERVALNUM="+str_intervalNum+"," +
								"USEFUL='"+str_useful+"'," +
								"NEEDAFFIRM='"+str_needAffirm+"'," +
								"CONTENT='"+dbManager.escape2Sql(str_content)+"'," +
								"Is_Open_File='"+str_isOpenFile+"'," +
								"File_Url='"+str_fileUrl+"'," +
								"Open_Params='"+str_openParams+"'," +
								"awokeStyle='"+str_awokeStyle+"' " +
							"Where id="+ id ;			
				}
				
				log.info("sql= "+sql);
				DbBean dbBean = new DbBean(DbBean.DefaultPoolName);
				dbBean.executeUpdate(sql);
				if( getId()==null){
					setId(int_id+"");
				
				} else {
					//先移除界面旧的显示行
					DefaultTableModel dtm = ((this.mainFrame.getReminderMainPanel().getMainTable().getModel())).getTableModel();
					int row = dtm.getRowCount();
					for (int i = 0; i<row; i++){
						Object t_obj = dtm.getValueAt( i,0);
						if(t_obj instanceof CodeNameBean){
							if( ((CodeNameBean)t_obj).getCode().equals( getId() ) ){
								dtm.removeRow( i );
								break;
							}
						}
					}
					// this.mf.getTable().remove( getTable().getSelectedRow() );
					// 再移除旧的任务信息
					this.mainFrame.getReminderMainPanel().removeAwoke( Integer.parseInt( this.getId() )) ;
				}
				
				//主界面增加定时任务
				this.mainFrame.getReminderMainPanel().addNewAwoke(getId(), str_title,
				                       str_beginTime, str_interval,
				                       Integer.parseInt(str_intervalNum),
				                       str_useful,
				                       str_needAffirm, str_content, str_awokeStyle );
				JOptionPane.showMessageDialog(this, this.msgDialog_infoSaveSuccess); //"Save Successfully！"
					
			} catch (SQLException e) {
				JOptionPane.showMessageDialog(this,e.getMessage(),"数据库操作失败",JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			
			} catch (Exception e) {
				JOptionPane.showMessageDialog(this,e.getMessage(),"操作失败",JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			}
			
		} else if( obj == btn_cancel){
			dispose();
		} else if( obj == minute){
			lblTx.setText("分提醒");
		} else if( obj == hour){
			lblTx.setText("小时提醒");
		} else if( obj == day){
			lblTx.setText("天提醒");
		} else if( obj == week){
			lblTx.setText("周提醒");
		} else if( obj == month){
			lblTx.setText("月提醒");
		} else if( obj == year){
			lblTx.setText("年提醒");
		} else if( obj == fileSelectButton){

			JFileChooser jFileChooser = new JFileChooser(); 
			jFileChooser.setCurrentDirectory(new File("."));
			// “打开”对话框
			//jFileChooser.showDialog(this,"打开...");
			jFileChooser.showOpenDialog(this);
			if(jFileChooser.getSelectedFile()==null
					|| jFileChooser.getSelectedFile().getPath()==null ){
				return;
			}
			String fileName=jFileChooser.getSelectedFile().getPath();
			if(fileName==null || fileName.trim().equals("")){
				return;
			} else {
				getOpenFileLocation().setText(fileName);
			}
			
		}
		
//		if (obj == week) {
//			getWeekSelector().setVisible(true);
//		}else{
//			getWeekSelector().setVisible(false);
//		}
		
	}

    private static String toStringValue(String text) {
    	return text==null?"":text.trim();
	}

	/**
     * 实现 ChangeListener 监听器的方法
     */
	public void stateChanged(ChangeEvent e) {
		Object obj = e.getSource();
		if (obj==mainTabPane){
			setLoopEnabled( isLoop.isSelected() );
		} else if( obj == btn_cancel){
			dispose();
		} else if( obj == minute){
			lblTx.setText("分提醒");
		} else if( obj == hour){
			lblTx.setText("小时提醒");
		} else if( obj == day){
			lblTx.setText("天提醒");
		} else if( obj == week){
			lblTx.setText("周提醒");
		} else if( obj == month){
			lblTx.setText("月提醒");
		} else if( obj == year){
			lblTx.setText("年提醒");
		}
	}

	private void fetchData(String p_id) {
		if(p_id==null)
			return;
		//id=p_id;
		this.setId( p_id ) ;
		// query
		String sql="";
		Connection conn = null;
		Statement stmt=null;
		ResultSet rs=null;
		try {
			conn= ApplicationContext.getInstance().getDataSourceManager().getConnection();
			sql="SELECT SortId, TITLE,TYPE, BEGINTIME, TIMETYPE, INTERVAL,INTERVALNUM, USEFUL, NEEDAFFIRM, CONTENT,AwokeStyle" +
					",Is_Open_File,File_Url,Open_Params FROM "+DirectorConstants.RMD_Awoke+" WHERE ID="+id;
			stmt=conn.createStatement();
			rs=stmt.executeQuery(sql);
			if(rs.next()){
				this.setTitle("修改提醒窗口") ;
				String awokeStyle = rs.getString("AwokeStyle");
				if (awokeStyle==null) {
					awokeStyle = DirectorConstants.AwokeStyle_Default;
				}
				getAwokeTitle().setText( rs.getString("TITLE") );
				getContent().setText( rs.getString("Content") );
				ComponentUtil.setSelectedItemByCode( getType(),rs.getString("TYPE") );
				ComponentUtil.setSelectedItemByCode( getAwokeStyle(),awokeStyle );
				java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				getBeginTime().setSelectedItem( sdf.format(rs.getTimestamp("BEGINTIME")) );

				getUseful().setSelected( rs.getString("USEFUL").equals("Y" ));
				getNeedAffirm().setSelected( rs.getString("NEEDAFFIRM").equals("Y" ));

				String isOpenFile=rs.getString("is_open_file");
				Boolean b_isOpenFile = null;
				if("1".equals(isOpenFile)){
					b_isOpenFile=true;
				}else{
					b_isOpenFile=false;
				}
				getIsOpenFile().setSelected( b_isOpenFile );
				getOpenFileLocation().setEnabled( b_isOpenFile );
				getFileSelectButton().setEnabled( b_isOpenFile );
				getOpenParams().setEnabled( b_isOpenFile );
				getOpenFileLocation().setText(rs.getString("File_Url"));
				getOpenParams().setText(rs.getString("Open_Params"));
				
				String interval=rs.getString("INTERVAL");
				int intervalNum=rs.getInt("INTERVALNUM");
				if(interval.trim().equals("0")){
					getIsLoop().setSelected( false );
					setLoopEnabled(false);  //enable is better than visible
//					getLoop_p1().setVisible(false);
				}else{
					getIsLoop().setSelected( true );
					setLoopEnabled(true);
//					getLoop_p1().setVisible(true);
					getIntervalNum().setText( intervalNum+"" );
					if(interval.equals("minute")){
						minute.setSelected(true);
						lblTx.setText("分提醒");
					} else if(interval.equals("hour")){
						hour.setSelected(true);
						lblTx.setText("小时提醒");
					} else if(interval.equals("day")){
						day.setSelected(true);
						lblTx.setText("天提醒");
					} else if(interval.equals("week")){
						week.setSelected(true);
						lblTx.setText("周提醒");
					} else if(interval.equals("month")){
						month.setSelected(true);
						lblTx.setText("月提醒");
					} else if(interval.equals("year")){
						year.setSelected(true);
						lblTx.setText("年提醒");
					}
				}
			}

		} catch (SQLException e1) {
			JOptionPane.showMessageDialog(this,e1.getMessage(),"查询失败",JOptionPane.ERROR_MESSAGE);
			e1.printStackTrace();						
		} finally{
			//释放资源
			wzw.util.DbUtils.closeQuietly(conn, stmt, rs);
		}
	}

	public void itemStateChanged(ItemEvent e) {
		Object obj = e.getSource();
		if( obj==isLoop ){
			setLoopEnabled( isLoop.isSelected() );
//			loop_p1.setVisible( isLoop.isSelected() );
			return ;
			
		} else if (obj==isOpenFile){
			getOpenFileLocation().setEnabled( isOpenFile.isSelected() );
			getFileSelectButton().setEnabled( isOpenFile.isSelected() );
			getOpenParams().setEnabled( isOpenFile.isSelected() );
			return ;
			
		} else if (obj==mainTabPane){
			setLoopEnabled( isLoop.isSelected() );
			return ;
			
		} else if( obj == btn_cancel){
			dispose();
			return ;
			
		} else if( obj == minute){
			lblTx.setText("分提醒");
		} else if( obj == hour){
			lblTx.setText("小时提醒");
		} else if( obj == day){
			lblTx.setText("天提醒");
		} else if( obj == week){
			lblTx.setText("周提醒");
		} else if( obj == month){
			lblTx.setText("月提醒");
		} else if( obj == year){
			lblTx.setText("年提醒");
		}
//		if (obj == week) {
//			getWeekSelector().setVisible(true);
//		}else{
//			getWeekSelector().setVisible(false);
//		}
		
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyPressed(KeyEvent e) {
		Object eventObj = e.getSource();
		int keyCode = e.getKeyCode();

		if( eventObj==getContent() ){
			if(keyCode==KeyEvent.VK_Z && DirectorComponentUtils.isControlDownOnly(e)){ //all objects
				editUndo();
				e.consume(); 
			}else if(keyCode==KeyEvent.VK_Y && DirectorComponentUtils.isControlDownOnly(e)){ //all objects
				editRedo();
				e.consume();  
			}
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	} 
    
}  //  @jve:decl-index=0:visual-constraint="10,10"
